package com.gt.login;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SaxParserUser extends DefaultHandler {

	private List<User> userList;
	private String tmpValue;
	private User tmpUser;
	String xmlFile;

	public SaxParserUser(String xmlFile) {
		this.xmlFile = xmlFile;
	}

	public List<User> parseFileAndGetListOfUsers() {

		SAXParserFactory spfFactory = SAXParserFactory.newInstance();
		try {
			SAXParser sParser = spfFactory.newSAXParser();
			sParser.parse(new File(xmlFile), this);
		} catch (ParserConfigurationException e) {
			
		} catch (SAXException e) {
		} catch (IOException e) {
			System.out.println("file not found"+xmlFile);
		}

		return userList;
	}

	@Override
	public void startElement(String uri, String localName, String elName,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, elName, attributes);
		if (elName.equalsIgnoreCase("users")) {
			userList = new ArrayList<User>();
		}
		if (elName.equalsIgnoreCase("user")) {
			tmpUser = new User();
		}
	}

	@Override
	public void endElement(String uri, String localName, String element)
			throws SAXException {
		super.endElement(uri, localName, element);
		if (element.equalsIgnoreCase("username")) {
			tmpUser.setUserName(tmpValue);
		}

		if (element.equalsIgnoreCase("password")) {
			tmpUser.setPassword(tmpValue);
		}
		if(element.equalsIgnoreCase("fname")){
			tmpUser.setFirstName(tmpValue);
		}
		if(element.equalsIgnoreCase("lname")){
			tmpUser.setLastName(tmpValue);
		}
		if(element.equalsIgnoreCase("address")){
			tmpUser.setAddress(tmpValue);
		}
		if(element.equalsIgnoreCase("phone")){
			tmpUser.setPhoneNo(tmpValue);
		}
		if (element.equalsIgnoreCase("user")) {
			userList.add(tmpUser);
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		super.characters(ch, start, length);
		tmpValue = new String(ch, start, length);
	}
}
